<template>
	<view>
		<!-- 顶部导航 -->
		<fa-navbar title="购买添加" ref="navbar"></fa-navbar>
		<view class="content">
			<u-form :model="form" ref="uForm">

				<!-- 精准定位的提示层 -->
				<view class="suggest-layer" :style="suggestPosition" v-show="showSuggest">
					<scroll-view scroll-y class="suggest-list">
						<!-- 结果列表 -->
						<view v-for="(item, index) in searchResults" :key="index" class="suggest-item"
							@click.stop="handleSelect(item)">
							<text class="suggest-text">{{ item.tc_name }}</text>
						</view>
					</scroll-view>
				</view>
				<u-form-item label="选择套餐" prop="name" label-width="200" class="search-wrapper" id="searchWrapper">
					<u-input v-model="form.name" placeholder="请选择" @input="handleSearchInput" class="custom-search"/>
					<!-- <u-select v-model="show" mode="single-column" :list="list1" @confirm="confirm"></u-select> -->
				</u-form-item>
				<!-- <u-form-item label="名称" prop="name" label-width="140">
					<u-input v-model="form.name" />
				</u-form-item> -->
				<u-form-item label="数量" prop="num" label-width="140">
					<u-input v-model="form.num" />
				</u-form-item>
				<!-- <u-form-item label="付款方式" prop="fkfs" label-width="200">
					<u-input v-model="form.fkfs" placeholder="请选择付款方式" @click="show2 = true"/>
					<u-select v-model="show2" mode="single-column" :list="list2" @confirm="confirm2"></u-select>
				</u-form-item> -->
				<u-form-item label="付款方式" label-width="140">

					<u-checkbox-group @change="checkboxGroupChange2">
						<u-checkbox v-model="item.checked" v-for="(item, index) in list2" :key="index"
							:name="item.name">{{item.name}}</u-checkbox>
					</u-checkbox-group>
				</u-form-item>
				<u-form-item label="微信支付金额" prop="xj_price" label-width="180">
					<u-input v-model="form.wx_price" />
				</u-form-item>
				<u-form-item label="现金支付金额" prop="xj_price" label-width="180">
					<u-input v-model="form.xj_price" />
				</u-form-item>
				<u-form-item label="上传图片" prop="jzqy" label-width="140">
					<u-upload :action="action" :auto-upload="true" @on-success='handleSuccess'
						@on-remove="handleRemove"></u-upload>
				</u-form-item>

				<u-form-item label="是否寄存" label-width="140">
					<u-radio-group v-model="is_value">
						<u-radio @change="radioChange" v-for="(item, index) in list" :key="index" :name="item.name"
							:disabled="item.disabled">
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</u-form-item>

				<u-checkbox-group @change="checkboxGroupChange">

					<u-checkbox v-model="item.checked" v-for="(item, index) in list_goods" :key="index"
						:name="item.goods_id" style="margin-right: 10px;">
						<view style="border-bottom: 1px solid #eee;margin-top: 10px;">
							<image :src="item.image" mode="" style="width: 100px;height: 100px;margin-left: 15px;">
							</image>
							<view class=""
								style="text-align: center;width: 130px;height: 32px;line-height: 32px;font-size: 14px;">
								{{item.goods_name}}
							</view>
							<view class=""
								style="text-align: center;width: 130px;height: 36px;line-height: 36px;font-size: 14px;">
								<span style="float: left;margin-right: 10px;">数量:</span><u-input
									v-model="item.goods_num" disabled="disabled" placeholder="请填写数量" />
							</view>
						</view>
					</u-checkbox>

				</u-checkbox-group>

			</u-form>
			<u-button @click="submit" :custom-style="customStyle">添加</u-button>
		</view>
		<u-toast ref="uToast" />
		<!-- 底部导航 -->
		<fa-tabbar></fa-tabbar>
	</view>
</template>

<script>
	import {
		archives
	} from '@/common/fa.mixin.js';
	// import FaUploadImage from '@/pages/publish/components/fa-upload-image/fa-upload-image.vue';
	export default {
		components: {
			// FaUploadImage
		},
		mixins: [archives],
		data() {
			return {
				searchKey: '',
				showSuggest: false,
				searchResults: [],
				suggestPosition: 'top:0;left:0;width:0', // 初始定位
				timer: null,
				action: 'http://leiyu99.com/api/common/upload',
				filesArr: [],
				user_id: 0,
				price: 0,
				list: [{
						name: '否',
						disabled: false
					},
					{
						name: '是',
						disabled: false
					},

				],
				list_goods: [],
				is_value: '否',
				is_value2: '微信',
				show: false,
				show2: false,
				list1: [],
				list2: [{
						name: '微信',
						checked: false,
						disabled: false
					},
					{
						name: '现金',
						checked: false,
						disabled: false
					},
					{
						name: '赊账',
						checked: false,
						disabled: false
					}
				],
				customStyle: {
					marginTop: '50px', // 注意驼峰命名，并且值必须用引号包括，因为这是对象
					color: '#333',
					border: 'none',
					background: '#e0ebdd',
				},
				form: {
					id: '',
					name: '',
					xj_price: 0,
					wx_price: 0,
					fkfs: '',
					fkfs_id: '',
					num: 1,
					type: 0,
					goods_ids: '',
					fileList: [],
				},
				rules: {
					name: [{
						required: true,
						message: '请输入套餐名称',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change'],
					}],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					]
				}
			};
		},
		onLoad(e) {
			let query = e || {};
			this.user_id = query.user_id || 0;
			this.is_update = true;
			// this.myTcAdd();
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		mounted() {
			// 获取搜索框位置信息
			this.getSearchPosition()
		},
		methods: {
			// 获取搜索框节点信息
			async getSearchPosition() {
				const query = uni.createSelectorQuery().in(this)
				query.select('#searchWrapper').boundingClientRect(res => {
					if (res) {
						this.searchRect = {
							top: res.top,
							left: res.left,
							width: res.width,
							height: res.height
						}
					}
				}).exec()
			},
			async handleSearchInput(val) {
				if (val) {
					await this.$nextTick()
					this.updatePosition()
					this.showSuggest = true
					let data = {
						keyword:val
					};
					let res = await this.$api.myTcAdd(data);
					var mockData = res.data;
					this.is_value = '否';
					this.form.type = 0;
					this.list_goods = [];
					this.searchResults = mockData;
				} else {
					this.showSuggest = false
				}
			},
			// 更新提示层位置
			updatePosition() {
				const {
					top,
					left,
					width,
					height
				} = this.searchRect
				const systemInfo = uni.getSystemInfoSync()
				const pxRatio = 750 / systemInfo.windowWidth
				this.suggestPosition = `
			            top: ${top + height + 10}px;
			            left: ${left}px;
			            width: ${width}px;
			          `
			},
			// 选中建议项
			handleSelect(item) {
				console.log(item);
				this.price = item.price;
				this.form.name = item.tc_name;
				this.form.id = item.id;
				this.showSuggest = false  // 确保关闭弹窗
			},
			myTcAdd: async function() {
				let data = {};
				let res = await this.$api.myTcAdd(data);
				this.list1 = res.data;
				this.is_value = '否';
				this.form.type = 0;
				this.list_goods = [];
			},
			radioChange(e) {
				console.log(e);
				if (e == '是') {
					this.form.type = 1;
					this.getListGoods();
				} else {
					this.form.type = 0;
					this.list_goods = [];
				}
			},
			checkboxGroupChange2(e) {
				console.log(e);
				const wx = '微信';
				const xj = '现金';
				if (e.includes(wx)) {
					this.form.wx_price = this.price*this.form.num
				} else {
					this.form.wx_price = 0
				}
				
				if (e.includes(xj)) {
					this.form.xj_price = this.price*this.form.num
				} else {
					this.form.xj_price = 0
				}
				var str = e.toString();
				this.form.fkfs = str;
			},
			getListGoods: async function() {
				if (!this.form.id) {
					this.is_value = '否';
					uni.showToast({
						title: '请选择套餐',
						icon: 'error',
						duration: 2000,
					});
					return false;
				}
				let data = {
					id: this.form.id
				};
				let res = await this.$api.myTcJiGoodsList(data);
				console.log(res, 'res')
				if (res.data.length) {
					this.list_goods = this.list_goods.concat(res.data);
				}
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过', this.form);
						var mem_id = this.user_id;
						this.$api.addTCAdd({
							user_id: this.user_id,
							name: this.form.name,
							num: this.form.num,
							id: this.form.id,
							type: this.form.type,
							xj_price: this.form.xj_price,
							wx_price: this.form.wx_price,
							goods_ids: this.form.goods_ids,
							fkfs: this.form.fkfs,
							fkfs_id: this.form.fkfs_id,
							fileList: this.form.fileList,
						}).then(res => {
							if (res.code == 1) {
								uni.showToast({
									title: '添加成功',
									icon: 'success',
									duration: 2000,
									success: function(res1) {
										setTimeout(() => {
											uni.redirectTo({
												url: '/pages/my/user_list'
											});
										}, 2000);
									},
								});
							} else {
								uni.showModal({
									title: '提示',
									content: res.msg,
									showCancel:false,
									success: function (res) {
										if (res.confirm) {
											console.log('用户点击确定');
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							}

						});

					} else {
						console.log('验证失败');
					}
				});
			},
			checkboxGroupChange(e) {
				
				var str = e.toString();
				console.log(str, 'e')
				this.form.goods_ids = str;
			},
			// 上传成功回调
			handleSuccess(res, index, lists) {
				uni.showToast({
					title: '上传成功',
					icon: 'success'
				});
				// 更新文件列表
				this.form.fileList = this.form.fileList.concat(res.data.url);

				console.log(this.form.fileList, 'concat')
			},
			// 文件被移除
			handleRemove(index, lists) {
				console.log(index, 'index')
				this.form.fileList.splice(index, 1);
				console.log(this.form.fileList, 'fileList')
			},
			confirm(e) {
				this.form.name = e[0].label;
				this.form.id = e[0].value;
			},
			confirm2(e) {
				this.form.fkfs = e[0].label;
				this.form.fkfs_id = e[0].value;
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	.content {
		width: 90%;
		margin: 10px auto;
		padding-bottom: 50px;
	}
</style>
<style lang="scss" scoped>
	/* 搜索框定制 */
	.custom-search {
		/deep/ .u-content {
			border: 4rpx solid #007AFF !important;
			border-radius: 8rpx !important;
		}
	}

	/* 精准定位层 */
	.suggest-layer {
		position: fixed;
		z-index: 100;
		background: #fff;
		border: 4rpx solid #007AFF;
		border-radius: 0 0 8rpx 8rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	/* 标题样式 */
	.suggest-title {
		padding: 20rpx 32rpx;
		border-bottom: 2rpx solid #eee;

		.title-text {
			font-size: 24rpx;
			color: #666;
		}
	}

	/* 列表项样式 */
	.suggest-list {
		max-height: 60vh;

		.suggest-item {
			padding: 28rpx 32rpx;

			&:active {
				background: #f5f5f5;
			}

			.suggest-text {
				font-size: 28rpx;
				color: #333;
				line-height: 1.4;
			}
		}
	}
</style>